package com.mec.fileTransfer.core;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.HashMap;
import java.util.Map;

public class RamdomAccessFlieBuffer {
	
	private static final Map<String, ThreadLocal<RandomAccessFile>> rafMap;
	
	static {
		rafMap = new HashMap<String, ThreadLocal<RandomAccessFile>>();
	}
	
	RamdomAccessFlieBuffer() {
	}
	
	synchronized static RandomAccessFile getRafFromBuffer(String fileName) throws FileNotFoundException {
		ThreadLocal<RandomAccessFile> rafLocal = rafMap.get(fileName);
		if(rafLocal == null) {
			//资源不存在需要创建！
			rafLocal = new ThreadLocal<RandomAccessFile>() {
				RandomAccessFile raf;
				@Override
				protected RandomAccessFile initialValue() {
					try {
						raf = new RandomAccessFile(fileName, "rwd");
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					}
					return raf;
				}
				
			};
			rafMap.put(fileName, rafLocal);
		}
		return rafLocal.get();
	}
	
	static void closeRaf() throws IOException {
		for(String fileHoleName : rafMap.keySet()) {
			ThreadLocal<RandomAccessFile> localRaf = rafMap.get(fileHoleName);
			System.out.println("归还raf[" + localRaf.get());
			localRaf.get().close();
		}
	}
	
}
